//
//  CZOauthController.swift
//  swiftweibo
//
//  Created by Apple on 15/11/24.
//  Copyright © 2015年 tzw. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZOauthController: UIViewController {
    override func loadView() {
        view = webView
        // 设置代理
        webView.delegate = self;
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权界面
        let request = NSURLRequest(URL: CZNetworkTool.sharedInstance.oauthURL())
        webView.loadRequest(request)

        // 设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    // MARK: - 加载accessToken
    func loadAccessToken(code: String){
        // 发送网络请求
        CZNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            // 判断是否有错误
            if error != nil && result == nil{
                // 告诉用户出错了
                SVProgressHUD.showErrorWithStatus("你的网络太不给力了", maskType: SVProgressHUDMaskType.Black)
           
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {()->Void in
                    self.close()
                    });
            }
            // 没有出错保存数据
            // 创建对象
          let userAccount =  CZUserAccount(dict: result!)
            // 保存对象
            userAccount.saveAccount()
//            print("userAccount:\(userAccount)")
            self.close()
            // 切换控制器
            AppDelegate.switchRootViewController(false)
        }
    
    }
    // MARK: - 实现按钮的点击方法
    func autoFill(){
        // 创建js代码
        let js = "document.getElementById('userId').value='790338345@qq.com'; document.getElementById('passwd').value='tzw13597234847';"
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    func close(){
        // 移除控制器
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: - 懒加载
    private lazy var webView = UIWebView()

}
// MARK: -  扩展加载网络请求的界面
extension CZOauthController: UIWebViewDelegate{
    // webview开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        // 显示一段时间就消失
        SVProgressHUD.showWithStatus("正在完命的加载...", maskType: SVProgressHUDMaskType.Black)
    }
    // 完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        // 移除控制器
        SVProgressHUD.dismiss()
    }
    // 每次加载链接都会调用这个方法,true可以加载，false就不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        // 判断用户点击的是什么
        if !urlString.hasPrefix(CZNetworkTool.sharedInstance.redirect_uri){
        return true
        }
//        print("\(urlString)")
        if let query = request.URL?.query{
            let codeString = "code="
            // 判断是否是以code=开头
            if query.hasPrefix(codeString){
//                print("\(urlString)")
                // 点击授权截取code先转成NSString
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                // 加载accessToken
                loadAccessToken(code)
            }else
            {
                // 点击取消
                self.close()
            }
        }
        return false
    }
}
